package vcp.client.GUI.mvc.view.custom;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JTextField;

import vcp.client.GUI.mvc.view.effects.ValidationLayerUI;

/**
 * <p>
 * custom input verifier class
 * </p>
 * 
 * @author VCP team
 * 
 */
public class CustomInputVerifier extends InputVerifier
{
	private final Pattern pattern;
	private final ValidationLayerUI validationUI;

	/**
	 * constructor
	 * 
	 * @param validationLayerUI
	 * @param pattern
	 */
	public CustomInputVerifier ( ValidationLayerUI validationLayerUI, Pattern pattern )
	{
		this.validationUI = validationLayerUI;
		this.pattern = pattern;
	}

	/**
	 * input check method
	 * 
	 * @param input
	 * @return true if input verified
	 */
	private boolean checkInput ( String input )
	{
		Matcher m = this.pattern.matcher(input);
		return m.matches();
	}

	/****************************************************************************************************************************
	 *** InputVerifier methods ***
	 ****************************************************************************************************************************/
	@Override
	public boolean verify ( JComponent input )
	{
		JTextField field = (JTextField) input;
		return this.checkInput(field.getText());
	}

	@Override
	public boolean shouldYieldFocus ( JComponent input )
	{
		boolean inputOK = this.verify(input);
		this.validationUI.setValid(inputOK);

		return true;
	}
}
